package routes

import (
	"illuminant/config"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Routes(port int) error {

	cnf := config.Get()
	r := gin.Default()
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"Content-Type", "Authorization", "access-control-allow-origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowOriginFunc: func(origin string) bool {
			return origin == "*"
		},
		MaxAge: 12 * time.Hour,
	}))

	apiV1 := r.Group("/api/v1")

	// no auth routes
	noAuthRoutes(apiV1)

	// use jwt middleware
	jwtRoutes(apiV1)

	// admin routes 这部分admin用于管理用, 实际系统中不开放
	adminRoutes(apiV1)

	// use jwt and rbac middleware
	rbacRoutes(apiV1)

	// static files
	// 这个route用来发布前端用, 前端编译之后, 放入public 文件夹即可
	r.Use(static.Serve("/", static.LocalFile(cnf.File.StaticDir, true)))

	r.NoRoute(func(c *gin.Context) {
		c.File("./public/index.html")
	})

	return r.Run(":" + strconv.Itoa(port))
}
